<template>
  <div class="container">

    <!-- 图像列表 -->
    <el-row>
      <div class="image-box">
        <div class="image-list">
          <Uploader :after-read="afterRead" v-model="fileList" multiple :max-count="9"
            :before-read="beforeRead" preview-size="100">
            <template #preview-cover="{ file }">
              <div class="preview-cover van-ellipsis">{{uploadSizeFormat(file.size)}}</div>
            </template>
          </Uploader>
        </div>
      </div>
    </el-row>

    <!-- 标题 -->
    <div class="row-line"></div>
    <el-row>
      <input class="works-title" type="text" v-model="works.title" placeholder="标题描述~"
        maxlength="255">
    </el-row>
    <div class="row-line"></div>
    <el-row class="row-description">
      <el-input type="textarea" class="works-description" :autosize="{ minRows: 4, maxRows: 6 }"
        v-model="works.description" placeholder="说一说此刻感想~" size="large" maxlength="1000"
        show-word-limit>
      </el-input>
    </el-row>

    <!-- 标签 -->
    <div class="row-line"></div>
    <el-row>
      <el-tag class="works-tag" :key="tag" v-for="tag in worksTag" size="large" closable
        :disable-transitions="false" @close="handleClose(tag)">
        # {{tag.name}}
      </el-tag>

      <el-input class="input-new-tag" v-if="inputVisible" v-model="inputValue" ref="saveTagInput"
        size="large" @keyup.enter="handleInputConfirm" @blur="handleInputConfirm" maxlength="10">
      </el-input>
      <el-button v-else class="button-new-tag" size="default" @click="showInput">+添加标签</el-button>
    </el-row>

    <!-- 权限 -->
    <div class="row-line"></div>
    <el-row>
      <el-switch v-model="works.isPermission" size="large" active-text="私有" inactive-text="全部可见" />
    </el-row>

    <!-- 地址 -->
    <div class="row-line"></div>
    <el-row>
      <div class="works-address">
        <div>{{placeName.mergername}}</div>
        <div class="works-address-right">
          地址
          <el-switch v-model="works.isPosition" size="large" @click="getPosition" />
        </div>
      </div>

    </el-row>

    <!-- 发布 -->
    <div class="row-line"></div>
    <div class="row-line"></div>
    <div class="row-line"></div>
    <el-row>
      <el-button class="works-btn" type="success" :loading="uploadLoading" size="large"
        @click="upload">发布
      </el-button>
      <div></div>
      <el-button class="works-btn" type="default" size="large" @click="addCookie">保存草稿
      </el-button>
    </el-row>
  </div>
</template>

<script scoped>
import { Uploader } from 'vant';
import VueCookies from 'vue-cookies'
import { ElMessage } from 'element-plus';
import { showError } from '../../base/map';
import { sizeFormat } from '../../utils';
export default {
  name: 'GUpload',
  components: {
    Uploader,
  },
  data () {
    return {
      fileList: [
      ],
      works: {
        description: "",
        title: "",
        isPermission: false,
        isPosition: false,
        longitude: null,
        latitude: null,
        permission: 1,
      },
      worksTag: [],
      placeName: { mergername: "" },
      inputVisible: false,
      inputValue: '',
      uploadLoading: false,
      cookieClock: null,
    };
  },
  mounted () {
    this.getCookie();
    this.cookieClock = setInterval(this.addCookie, 1000);
  },
  unmounted () {
    clearInterval(this.cookieClock);
  },
  methods: {
    //图片校验
    beforeRead (file) {
      //多文件校验
      if (file instanceof Array) {
        for (var index in file) {
          if (file[index].type == 'image/jpeg' || file[index].type == 'image/png' || file[index].type == 'image/gif') {
            continue;
          } else {
            ElMessage({
              message: '部分图片格式不正确',
              grouping: true,
              type: 'error',
              duration: 2000,
            })
            file.splice(index, 1);
          }
        }
        return true;
      }
      //单文件校验
      if (file.type == 'image/jpeg' || file.type == 'image/png' || file.type == 'image/gif') {
        return true;
      } else {
        ElMessage({
          message: '请上传 jpg,png,jpeg,gif 格式图片',
          grouping: true,
          type: 'error',
          duration: 2000,
        })
        return false;
      }
    },
    afterRead (file) {
      console.log(file);
      // 图片加载完毕后执行
    },
    //发布
    upload () {
      if (this.fileList == [] || this.fileList.length == 0) {
        ElMessage({
          message: '请输入至少一张图片',
          grouping: true,
          type: 'error',
          duration: 2000,
        })
        return;
      }
      this.uploadLoading = true;
      //1. 内容检查
      if (this.works.isPermission) {
        this.works.permission = 0;
      } else {
        this.works.permission = 1;
      }
      this.$axios.post("/works/check", { "works": this.works, "worksTags": this.worksTag })
        .then(res => {
          return res;
        })
        .then(res => {
          //2.添加初始化作品
          if (!res.flag) {
            this.uploadLoading = false; return;
          }
          return this.$axios.post("/works", { "works": this.works, "worksTags": this.worksTag })
            .then(res => {
              return res;
            })
            .then(res => {
              //3.上传图片数据
              if (!res.flag) {
                this.uploadLoading = false; return;
              }
              var forms = new FormData();
              forms.append("worksId", res.data);
              //FormData不能直接放数组，要遍历。。。
              for (var key in this.fileList) {
                forms.append("files", this.fileList[key].file);
              }
              forms.append("firstImg", 1);
              this.$axios({
                method: 'post',
                url: '/works/upload',
                data: forms,
              }).then((res) => {
                if (res.flag) {
                  ElMessage({
                    message: res.msg,
                    type: 'success',
                    duration: 2000,
                  })
                }
                this.uploadLoading = false;
              })
            })
        })
    },
    //______________________标签__________________________________
    handleClose (tag) {
      this.worksTag.splice(this.worksTag.indexOf(tag), 1);
    },

    showInput () {
      this.inputVisible = true;
      this.$nextTick(() => {
        this.$refs.saveTagInput.$refs.input.focus();
      });
    },

    handleInputConfirm () {
      let inputValue = this.inputValue;
      if (inputValue) {
        if (this.worksTag.length >= 5) {
          ElMessage({
            message: '标签最多5个',
            grouping: true,
            type: 'error',
            duration: 2000,
          })
          this.inputVisible = false;
          return;
        }
        this.worksTag.push({ name: inputValue });
      }
      this.inputVisible = false;
      this.inputValue = '';
    },
    //展示详细地址
    showRealPosition (longitude, latitude) {
      this.$axios.get("/geo/placename/" + longitude + "/" + latitude + "")
        .then((res) => {
          if (res.flag) {
            this.placeName = res.data.name;
          }
        })
    },
    getPosition () {
      if (this.works.isPosition) {
        // 获取地理位置信息
        console.log("获取地址");
        let that = this;
        navigator.geolocation.getCurrentPosition(
          (position) => {
            console.log('当前位置信息：', position)
            let longitude = position.coords.longitude
            let latitude = position.coords.latitude
            that.works.longitude = longitude;
            that.works.latitude = latitude;
            that.showRealPosition(longitude, latitude);
          },
          (error) => {
            console.log("错误");
            showError(error);
          })
      } else {
        this.works.longitude = null;
        this.works.latitude = null;
        this.placeName = "";
      }
    },
    uploadSizeFormat (size) {
      return sizeFormat(size);
    },
    // //获取缓存数据
    getCookie () {
      console.log(VueCookies.get("uploadCookie"));
      var cookie = VueCookies.get("uploadCookie");
      if (cookie == null || cookie == {}) { return; }
      this.works = cookie.works;
    },
    // //草稿
    addCookie () {
      var uploadCookie = {};
      uploadCookie.works = this.works;
      VueCookies.set("uploadCookie", uploadCookie);
      console.log("定时存储上传数据")
    },
  },
}
</script>

<style scoped>
.container {
  padding: 10px;
}
.image-box {
  height: 100px;
  width: 100%;
  overflow-x: scroll;
  overflow-y: hidden;
  white-space: nowrap;
}
.image-list {
  height: 100px;
  width: 980px;
}
.preview-cover {
  position: absolute;
  bottom: 0;
  box-sizing: border-box;
  width: 100%;
  padding: 4px;
  color: #fff;
  font-size: 12px;
  text-align: center;
  background: rgba(0, 0, 0, 0.3);
}
.works-title {
  border: none;
  font-size: 25px;
}
.works-title::placeholder {
  color: #9e9fa2;
}
.works-description {
  width: 100%;
  font-size: 16px;
}
.works-description::placeholder {
  color: gainsboro;
}
.row-description >>> .el-textarea__inner {
  border: none;
  border-radius: none;
  border-top: 1px solid gainsboro;
  border-bottom: 1px solid gainsboro;
  padding-top: 10px;
  box-shadow: none;
}
.works-tag {
  margin: 2px;
  font-size: 15px;
}
.button-new-tag {
  margin: 2px;
}
.works-btn {
  width: 100%;
  margin-bottom: 10px;
}
.works-address {
  width: 100%;
}
.works-address-right {
  float: right;
}
</style>